
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/utils/EventBus.dart';
import 'package:flutter_app/utils/http.dart';
import 'package:flutter_app/views/carList.dart';
import 'package:flutter_app/views/leftPage.dart';
import 'package:flutter_app/views/warningCard.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePage createState() => _HomePage();
}

class _HomePage extends State<HomePage> {

  String debugLable = 'Unknown';
  final JPush jpush = new JPush();
  var bus = new EventBus();

  int _selectedIndex = 0;
  var _pageController = PageController();
  DateTime _lastPressed;
  List<Widget> pages = <Widget>[
    WarningCard(),
    // WarningCardList(),
    CardList()

  ];

  //  顶部导航的问题
  double elevationDs = 0;

  @override
  void initState(){
    super.initState();
    initPlatformState();
  }

  bindJPushUser(registrationId) async{
    ResultData list = await HttpRequest.post('/webauth/jpush/bindJPushUser', {
      'registrationId':registrationId
    });
    // details = card.data;
  }

  Future<void> initPlatformState() async {
    String platformVersion;

    try {
      jpush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
            print("flutter onReceiveNotification: $message");
            setState(() {
              debugLable = "flutter onReceiveNotification: $message";
            });
          },
          onOpenNotification: (Map<String, dynamic> message) async {
            print("flutter onOpenNotification: $message");
            _pageController.jumpToPage(0);
            setState(() {
              debugLable = "flutter onOpenNotification: $message";
            });
          },
          onReceiveMessage: (Map<String, dynamic> message) async {
            print("flutter onReceiveMessage: $message");
            bus.emit("push", "1");
            setState(() {
              debugLable = "flutter onReceiveMessage: $message";
            });
          },
          onReceiveNotificationAuthorization:
            (Map<String, dynamic> message) async {
              print("flutter onReceiveNotificationAuthorization: $message");
              setState(() {
                debugLable = "flutter onReceiveNotificationAuthorization: $message";
              });
          });
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    jpush.setup(
      appKey: "a050680ed4f16e1a850e06ad", //你自己应用的 AppKey
      channel: "theChannel",
      production: false,
      debug: true,
    );
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    // Platform messages may fail, so we use a try/catch PlatformException.
    jpush.getRegistrationID().then((rid) {
      print("flutter get registration id : $rid");
      bindJPushUser(rid);
      setState(() {
        debugLable = "flutter getRegistrationID: $rid";
      });
    });

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      debugLable = platformVersion;
    });
  }

  setIndex(index){
    setState(() {
      _selectedIndex = index;
      if(index == 0){
        elevationDs = 0;
      }else{
        elevationDs = 3;
      }
    });
  }
  // setState(() =>
  //   bottoms = PreferredSize(child: Container())
  // );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: Builder(builder: (BuildContext ctx) {
            return IconButton(
              icon: Container(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: AssetImage('assets/images/app.png'),
                  ),
                ),
              ),
              onPressed: () {
                // 打开一个左侧菜单
                Scaffold.of(ctx).openDrawer();
              });
          }),
          elevation: elevationDs,
          centerTitle: true,
          title: Text("园区安防"),
          // bottom: bottoms
        ),
        // tab的两个页面, WillPopScope返回是否退出
        body:WillPopScope(
          //两次返回退出
          onWillPop: () async {
            if (_lastPressed == null ||
                DateTime.now().difference(_lastPressed) > Duration(seconds: 1)) {
              //两次点击间隔超过1秒则重新计时
              _lastPressed = DateTime.now();
              return false;
            }
            return true;
          },
          child:PageView.builder(
            itemBuilder: (ctx, index) => pages[index],
            itemCount: pages.length,
            controller: _pageController,
            //               BouncingScrollPhysics ：允许滚动超出边界，但之后内容会反弹回来。
            //               ClampingScrollPhysics ： 防止滚动超出边界，夹住 。
            //               AlwaysScrollableScrollPhysics ：始终响应用户的滚动。
            //               NeverScrollableScrollPhysics ：不响应用户的滚动。
            physics: NeverScrollableScrollPhysics(),
            onPageChanged: (index) {
              setIndex(index);
            },
          ),
        ),
        // 底部
        bottomNavigationBar:BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          items: [
            BottomNavigationBarItem(
              backgroundColor: Colors.blue,
              icon: Icon(Icons.admin_panel_settings),
              label: "园区安防",
            ),
            BottomNavigationBarItem(
              backgroundColor: Colors.blue[600],
              icon: Icon(Icons.directions_car),
              label: "车辆查询",
            )
          ],
          currentIndex: _selectedIndex,
          onTap: (index) {
            _pageController.jumpToPage(index);
            // setState(() =>
            //     _selectedIndex = index
            // );
          },
        ),
        // 被打开的侧页
        drawer: Drawer(
          child:LeftPage()
        )
    );
  }
}